<?php

namespace App\Service\Moment;

// use App\Constants\ErrorCode;
use App\Cache\UserRemarkCache;
use App\Helpers\DateUtil;
use App\Helpers\RedisUtil;
use App\Model\Moment;
use App\Model\Setting\SettingUserLevel;
use App\Model\User;
use App\Model\UserFollow;
use App\Model\UserProfile;
use App\Model\UserSocialProfile;
use App\Model\UserTag;
use App\Service\User\UserBaseService;
use Hyperf\DbConnection\Db;

/**
 * 动态列表
 */
class MomentListService extends UserBaseService
{
    public function handle()
    {
        $type = trim($this->request->input('type', 'rec'));
        $page = $this->request->input('page', 1);
        $profile = UserProfile::getProfile($this->userId);
        $ret['list'] = $this->platform == 2
            ? $this->packData($type, $this->userId, $page, $profile->gender)
            : $this->packIosData($this->userId, $page, $profile->gender);
        return $ret;
    }

    /**
     * 获取数据
     */
    function packData($type = 'rec', $userId, $page = 1, $gender = 0)
    {
        $showGender = $gender == 1 ? 0 : 1;
        switch ($type) {
                //我的
            case 'my':
                $list = Moment::getUserList($userId, $page, $this->pageNum, -1, $userId);
                break;
                //关注
            case 'follow':
                $followUsers = UserFollow::getFollowList($userId);
                $list = Moment::getUserList($followUsers, $page, $this->pageNum, -1, $userId);
                break;
                //热门
            case 'hot':
                $list = Moment::getList($page, $this->pageNum, $showGender, 'hot');
                break;
                //默认-推荐
            default:
                $list = Moment::getList($page, $this->pageNum, $showGender);
        }
        $userIds = array_column($list, 'user_id');
        $profiles = [];
        $data = UserProfile::getUsersProfile($userIds);
        foreach ($data as $item) {
            $profiles[$item['user_id']] = $item;
        }
        $data = [];

        $socialTags = UserSocialProfile::getBatchProfile($userIds, 'tag');

        array_walk($list, function ($item) use (&$data, $userId, $profiles,$socialTags) {
            $momentUserId = is_array($item) ? $item['user_id'] : $item->user_id;
            $momentItem = Moment::buildItem($item, $profiles[$momentUserId] ?? null, $userId);
            $momentItem['show_comment'] = 0;
            $momentItem['level'] = SettingUserLevel::getUserLevel($profiles[$momentUserId]);
            $momentItem['chat_type'] = $this->checkChatBefore($momentUserId) ? 1 : 2;
            $momentItem['remark'] = ($momentUserId != $userId ? (new UserRemarkCache())->getRemark($userId, $momentUserId) : '');
            $momentItem['tags'] = array_merge(
                [DateUtil::dateDiff($profiles[$momentUserId]['birthday'], date('Y-m-d'), 'Y').'岁'],
                $socialTags[$momentUserId] ?? []
            );
            array_push($data, $momentItem);
        });
        //伴侣
        if ($this->appId == 102) $this->packJikeliaoData($data, $profiles);
        return $data;
    }

    function checkChatBefore($chatUserId = 0)
    {
        return RedisUtil::get("chat_start_{$this->userId}_{$chatUserId}");
    }

    /**
     * 额外数据（同城陌玩）
     */
    function packJikeliaoData(&$list = [], $profiles = [])
    {
        /**
         * 添加在线,个性签名,他的标签,视频url,imaccount 
         */
        foreach ($list as &$momentItem) {
            $profile = $profiles[$momentItem['user_id']];
            if (!is_array($profile)) $profile = $profile->toArray();
            $momentItem = array_merge($momentItem, [
                'online_status' => $profile['online'],
                'self_intro' => $profile['self_intro'],
            ]);
        }
        $this->packTags($list);
        return;
    }

    /**
     * IOS数据
     */
    function packIosData($userId = 0, $page = 1, $gender = 0)
    {
        $list = $this->packIosList();
        $userIds = array_column($list, 'user_id');
        $profiles = [];
        $data = UserProfile::getUsersProfile($userIds);
        foreach ($data as $item) $profiles[$item['user_id']] = $item;
        $data = [];
        array_walk($list, function ($item) use (&$data, $userId, $profiles) {
            $momentUserId = is_array($item) ? $item['user_id'] : $item->user_id;
            $momentItem = Moment::buildItem($item, $profiles[$momentUserId] ?? null, $userId);
            $momentItem['pub_time'] = '';
            array_push($data, $momentItem);
        });
        return $data;
    }

    function packIosList($page = 1, $pageNum = 20)
    {
        $where = [
            ['moment.status', Moment::STATUS_OK],
            ['user.status', User::STATUS_OK],
            ['video', '<>', '']
        ];
        $start = ($page - 1) * $pageNum;
        $query = Db::table('moment')->join('user', function ($join) {
            $join->on('user.id', '=', 'moment.user_id');
        })->where($where); //->whereRaw('locate("1400000", phone)=1')
        $selectField = ['moment.*'];
        return $query->where($where)->select($selectField)->offset($start)->limit($pageNum)->orderBy('moment.id', 'desc')->get()->toArray();
    }
}
